from typing import List
from flask import current_app
from models.dict import Dict
from models.dict_item import DictItem
from services import BaseService


class DictService(BaseService):
    """
    字典模块业务处理类
    """

    def get_by_dict_type(self, dictType):
        """
        根据字典类型获取字典数据
        :param dictType: 字典类型
        :return: 字典数据
        """
        dict = current_app.config["DICT_ENUM_MAP"].get(dictType)
        res = []
        if dict is not None:
            for item in dict.get("items"):
                res.append(
                    {"value": item.get("dictItemValue"), "label": item.get("name")}
                )
        else:
            # 从数据库中获取
            record: Dict = (
                self.db.session.query(Dict).filter(Dict.code == dictType).first()
            )
            if record is not None:
                dictItemList: List[DictItem] = (
                    self.db.session.query(DictItem)
                    .filter(DictItem.dictId == record.id)
                    .all()
                )
                for item in dictItemList:
                    res.append({"value": item.code, "label": item.name})

        return res
